<template>
  <md-main>
    <el-collapse-transition>
      <div class="md-body mb20" v-show="showSearch">
        <el-form :model="search" ref="search" size="small" :inline="true">
          <el-form-item label="字典名称" prop="dictName">
            <el-input v-model="search.dictName" placeholder="请输入字典名称" clearable class="w150" />
          </el-form-item>
          <el-form-item label="字典类型" prop="dictType">
            <el-input v-model="search.dictType" placeholder="请输入字典类型" clearable class="w150" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <md-dict-select :options="statusList" :props="{label:'label',value:'value'}" v-model="search.status" placeholder="请选择状态" class="w150"></md-dict-select>
          </el-form-item>
          <!-- <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" class="w250" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item> -->
          <el-form-item>
            <md-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery()">搜索</md-button>
            <md-button icon="el-icon-refresh" size="mini" @click="handleQueryReset()">重置</md-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="md-body md-table">

      <md-toolbar>
        <md-button type="primary" size="small" plain :prems="['system:dict:add']" @click="handleAdd()">新增</md-button>
        <md-button type="success" size="small" plain :prems="['system:dict:remove']" :disabled="tableSelectIds.length===0" @click="handleDelete()">批量删除</md-button>

        <template slot="right">
          <md-button size="mini" icon="el-icon-search" circle @click="showSearch=!showSearch"></md-button>
          <md-button type="primary" size="mini" icon="el-icon-refresh" circle @click="getTableDataList()"></md-button>
        </template>
      </md-toolbar>

      <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleTableSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="字典编号" align="center" prop="dictId" min-width="80px" />
        <el-table-column label="字典名称" align="center" prop="dictName" min-width="200px" :show-overflow-tooltip="true" />
        <el-table-column label="字典类型" align="center" min-width="180px" :show-overflow-tooltip="true">
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleOpenDictData(row)">{{ row.dictType }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" min-width="100px">
          <template slot-scope="{ row }">
            <md-dict-tag :options="statusList" :props="{label:'label',value:'value'}" :value="row.status"></md-dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="150px" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180px">
          <template slot-scope="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="150px">
          <template slot-scope="scope">
            <md-button size="mini" type="text" icon="el-icon-edit" :prems="['system:dict:edit']" @click="handleUpdate(scope.row)">修改</md-button>
            <md-button size="mini" type="text" icon="el-icon-delete" :prems="['system:dict:remove']" @click="handleDelete(scope.row)">删除</md-button>
          </template>
        </el-table-column>
      </el-table>

      <md-pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="search.pageIndex" :limit.sync="search.pageSize" @pagination="getTableDataList" />
    </div>

    <!-- 添加或修改配置对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="80px" label-position="right">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="request.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="request.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <md-dict-radio-group :options="statusList" :props="{label:'label',value:'value'}" v-model="request.status"></md-dict-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="request.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <md-button type="primary" size="small" @click="handleSubmit">确 定</md-button>
        <md-button size="small" @click="handleCancel">取 消</md-button>
      </div>
    </el-dialog>

    <!--字典数据-->
    <el-drawer :title="dictDataDrawer.title" :visible.sync="dictDataDrawer.open" append-to-body direction="rtl" size="800px" :before-close="handleDrawerBeforeClose">
      <md-system-dict-data :params="dictDataDrawer.params" />
    </el-drawer>
  </md-main>
</template>

<script>
import { insertDictType, updateDictType, listPageDictType, delDictType, getDictType } from '@/api/system/dict.type.service.js'
import MdSystemDictDataComponent from './data.vue'
export default {
  name: 'MdSystemDictComponent',
  components: {
    'md-system-dict-data': MdSystemDictDataComponent
  },
  data () {
    return {
      statusEnum, statusList,
      // 显示隐藏查询条件
      showSearch: true,
      // 查询参数
      search: searchParams,
      // 创建时间
      dateRange: [],
      // 列表加载
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      // 已选择的列表数据
      tableSelectIds: [],
      // 添加/编辑请求参数
      request: requestParams,
      rules: rules,
      // 添加/编辑弹窗
      dialog: {
        title: '添加字典',
        open: false
      },
      // 字典数据抽屉
      dictDataDrawer: {
        title: null,
        open: false,
        params: null
      }
    }
  },
  mounted () {
    this.getTableDataList()
  },
  methods: {
    /** 获取字典数据 */
    async getTableDataList () {
      this.tableLoading = true
      this.tableData = []

      try {
        const res = await listPageDictType(this.search)

        this.tableData = res.data.items
        this.tableTotal = res.data.totalItems
      } catch (error) {
        console.log(error)
      }
      this.tableLoading = false
    },
    /** 表格复选框事件 */
    handleTableSelectionChange (event) {
      this.tableSelectIds = event.map(m => { return m.dictId })
    },
    /** 搜索 */
    handleQuery () {
      this.search.pageIndex = 1

      this.getTableDataList()
    },
    /** 重置搜索 */
    handleQueryReset () {
      this.search = { ...searchParams }

      this.getTableDataList()
    },
    // 重置表单数据
    handleReset () {
      this.request = { ...requestParams }
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 删除字典 */
    async handleDelete (row) {
      try {
        const ids = row?.dictId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delDictType(ids)

        this.$message.success('删除成功')

        this.handleQuery()
      } catch (error) {
        console.log(error)
      }
    },
    /** 添加字典 */
    async handleAdd () {
      try {
        this.handleReset()

        this.dialog.title = '添加字典'

        this.dialog.open = true

        this.request = { ...requestParams }
      } catch (error) {
        console.log(error)
      }
    },
    /** 修改字典 */
    async handleUpdate (row) {
      try {
        this.handleReset()

        const res = await getDictType(row.dictId)

        this.request = res.data

        this.dialog.open = true

        this.dialog.title = '修改字典'

      } catch (error) {
        console.log(error)
      }
    },
    /** 提交 */
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.request })

          await (params.dictId === undefined ? insertDictType : updateDictType)(params)

          this.$message.success(params.dictId === undefined ? '添加成功' : '修改成功')

          this.dialog.open = false

          this.handleQuery()
        } catch (error) {
          console.log(error)
        }
      })
    },
    /** 取消 */
    handleCancel () {
      this.dialog.open = false

      this.handleReset()
    },
    /** 打开字典数据抽屉弹窗 */
    handleOpenDictData (row) {
      this.dictDataDrawer.title = `字典管理 - ${row.dictName} - ${row.dictType}`
      this.dictDataDrawer.params = { ...row }
      this.dictDataDrawer.open = true
    },
    /** 关闭字典数据抽屉 */
    handleDrawerBeforeClose (done) {
      this.dictDataDrawer.title = null
      this.dictDataDrawer.params = null
      this.dictDataDrawer.open = false
      done()
    }
  }
}
const searchParams = {
  dictName: undefined,
  dictType: undefined,
  status: undefined,
  createBy: undefined,
  updateBy: undefined,
  beginDate: undefined,
  endDate: undefined,
  orderBy: 'create_time',
  isDesc: true,
  pageIndex: 1,
  pageSize: 10
}

const requestParams = {
  dictId: undefined,
  dictType: undefined,
  dictName: undefined,
  status: '0',
  remark: undefined
}

const rules = {
  dictName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  dictType: [{ required: true, message: '请输入字典类型', trigger: 'blur' }]
}

// 字典状态
const statusEnum = {
  '0': { label: '正常', type: 'success' },
  '1': { label: '停用', type: 'danger' }
}
const statusList = Object.keys(statusEnum).map(m => { return { value: m, label: statusEnum[m].label } })
</script>